<template>
  <basic-container class="task-dispatch" v-loading="loading" element-loading-text="数据加载中...">
    <dataList
      ref="taskDispatch"
      :pageInfo="pager"
      :listData="tableData"
      :menuList="getPermissions('sys_quartz_job_add') ? ['add','export',{log: '日志'}] : ['export',{log: '日志'}]"
      :listLayout="['menu','filter']"
      :filterList="filterList"
      @menu-click="handleMenuClick"
    >
      <el-table :data="tableData" align="left" ref="multipleTable">
        <el-table-column label="序号" type="index" :index="getIndex" width="55" />
        <el-table-column label="任务ID" prop="id" width="65" />
        <el-table-column label="任务名称" prop="jobName" width="150" show-overflow-tooltip />
        <el-table-column label="Bean名称" prop="beanName" width="150" show-overflow-tooltip />
        <el-table-column label="执行方法" prop="methodName" width="150" show-overflow-tooltip />
        <el-table-column label="cron表达式" prop="cronExpression" width="150" show-overflow-tooltip />
        <el-table-column label="描述" prop="description" width="150" show-overflow-tooltip />
        <el-table-column label="状态" prop="isPause" width="100">
          <template slot-scope="scope">
            <span :class="scope.row.isPause ? 'isPause' : 'isPauseTrue'">{{scope.row.isPause ? '暂停' : '启动'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="参数" prop="params" width="120" show-overflow-tooltip />
        <el-table-column label="创建日期" prop="createTime" width="160" />
        <el-table-column width="220" label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" v-if="getPermissions('sys_quartz_job_edit')" @click="handleUpdate(scope.row,scope.index)">编辑</el-button>
            <el-button type="text" v-if="getPermissions('sys_quartz_job_del')" @click="handleDelete(scope.row,scope.index)">删除</el-button>
            <el-button type="text" v-if="getPermissions('sys_quartz_job_execution')" @click="executionTask(scope.row,scope.index)">执行</el-button>
            <el-button
              type="text"
              v-if="getPermissions('sys_quartz_job_update_status') && scope.row.isPause === true"
              @click="updateQStatus(scope.row,scope.index)"
            >启用</el-button>
            <el-button
              type="text"
              v-if="getPermissions('sys_quartz_job_update_status') && scope.row.isPause === false"
              @click="updateZStatus(scope.row,scope.index)"
            >暂停</el-button>
          </template>
        </el-table-column>
      </el-table>
    </dataList>
    <v-dialog
      :title="isEdit ? '编辑' : '新增'"
      :show.sync="dialogVisible"
      width="1200px"
      v-loading="dialogLoading"
      @beforeClose="beforeClose"
      element-loading-text="正在保存..."
      v-if="dialogVisible"
    >
      <el-form ref="taskDispatchForm" :model="tableOption" label-width="140px" :rules="tableOption_rules" class="form-wrap">
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-halfCharCode v-model="tableOption.jobName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="Bean名称" prop="beanName">
          <el-input v-halfCharCode v-model="tableOption.beanName" placeholder="请输入Bean名称" />
        </el-form-item>
        <el-form-item label="执行方法" prop="methodName">
          <el-input v-halfCharCode v-model="tableOption.methodName" placeholder="请输入执行方法" />
        </el-form-item>
        <el-form-item label="cron表达式" prop="cronExpression">
          <el-input v-halfCharCode v-model="tableOption.cronExpression" placeholder="请输入cron表达式" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-halfCharCode v-model="tableOption.description" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="负责人" prop="personInCharge">
          <el-input v-halfCharCode v-model="tableOption.personInCharge" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="报警邮箱" prop="email">
          <el-input v-halfCharCode v-model="tableOption.email" placeholder="请输入报警邮箱" />
        </el-form-item>
        <el-form-item label="子任务ID" prop="subTask">
          <el-input v-halfCharCode v-model="tableOption.subTask" placeholder="请输入子任务ID" />
        </el-form-item>
        <el-form-item label="任务失败后是否暂停" prop="pauseAfterFailure">
          <el-radio-group v-model="tableOption.pauseAfterFailure" size="small">
            <el-radio :label="false">是</el-radio>
            <el-radio :label="true">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="isPause">
          <el-radio-group v-model="tableOption.isPause" size="small">
            <el-radio :label="false">启用</el-radio>
            <el-radio :label="true">暂停</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="参数" prop="params" class="full">
          <el-input v-halfCharCode type="textarea" maxlength="100" placeholder="请输入参数" v-model="tableOption.params" />
        </el-form-item>
      </el-form>
      <span slot="foot">
        <el-button v-throttle="[commit]">{{isEdit ? '修 改' : '保 存'}}</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </span>
    </v-dialog>
    <task-deipatch-log ref="taskDeipatchLog"></task-deipatch-log>
  </basic-container>
</template>

<script>
import { fetchList, getObj, addObj, putObj, executionObj, delObj } from "@/admin/api/sys-quartz-job";
import taskDeipatchLog from "~/admin/views/system-manage/sys-conf/task-deipatch-log";
export default {
  name: "task-dispatch",
  components: { taskDeipatchLog },
  provide () {
    return {
      initList: this.getListData
    };
  },
  beforeMount () {
    this.getListData()
    this.dictTypes = this.getDict('dict_type')
  },
  mounted () {
    this.$refs.taskDispatch.setFilter(new Map([['jobName', '']]))
  },
  data () {
    return {
      tableData: [],
      // 请求参数
      params: {
        current: 1,
        size: 10
      },
      // 分页
      pager: {
        total: 0, // 总页数
        current: 1, // 当前页数
        size: 10 // 每页显示多少条
      },
      filterList: [{ label: '任务名称', inputType: 'input', name: 'jobName', placeholder: '请输入任务名称' }],
      // 页面loading
      loading: false,
      dictTypes: [],
      // 新增、编辑弹框
      isEdit: false,
      dialogLoading: false,
      dialogVisible: false,
      tableOption: {
        jobName: '',
        beanName: '',
        methodName: '',
        cronExpression: '',
        description: '',
        personInCharge: '',
        email: '',
        subTask: '',
        pauseAfterFailure: false,
        isPause: false,
        params: ''
      },
      tableOption_rules: {
        jobName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        beanName: [{ required: true, message: '请输入Bean名称', trigger: 'blur' }],
        methodName: [{ required: true, message: '请输入执行方法', trigger: 'blur' }],
        cronExpression: [{ required: true, message: '请输入Cron表达式', trigger: 'blur' }],
        description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
        personInCharge: [{ required: true, message: '请输入任务负责人', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 获取列表
    getListData (params = {}) {
      this.loading = true;
      let requestData = { ...this.params, ...params };
      for (let key in requestData) {
        if (requestData[key] === '' || requestData[key] === null || requestData[key] === undefined) {
          requestData = {
            current: 1,
            size: 10
          }
        }
      }
      fetchList(requestData)
        .then(res => {
          const { current, size, total, records } = res.data.data;
          this.tableData = records;
          this.params = requestData;
          this.pager = { total, current, size };
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 菜单点击监听
    handleMenuClick (type) {
      switch (type) {
        case "add":
          this.dialogVisible = true;
          break;
        case "export":
          this.publicExport('定时任务数据', '/admin/task/jobs/download', this.params);
          break;
        case "log":
          this.$refs.taskDeipatchLog.managementOpen()
          break;
        default:
          this.$message(type);
          break;
      }
    },
    // 编辑
    handleUpdate (row, index) {
      this.tableOption = row
      this.isEdit = true
      this.dialogVisible = true
    },
    // 删除
    handleDelete (row) {
      this.$confirm('是否确认删除ID为"' + row.id + '"的数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        let ids = [];
        ids.push(row.id);
        return delObj(ids)
      }).then(() => {
        this.getListData({ current: 1 })
        this.$notify.success('删除成功')
      })
    },
    // 弹框保存
    commit () {
      this.$refs.taskDispatchForm.validate(valid => {
        if (valid) {
          this.dialogLoading = true
          if (this.isEdit) {
            putObj(this.tableOption).then(res => {
              if (res.data.code === 0) {
                this.$notify.success('修改成功')
                this.dialogLoading = false
                this.handleCancel()
              } else {
                this.$notify.error('修改失败')
                this.dialogLoading = false
                this.handleCancel()
              }
            }).catch(() => {
              this.dialogLoading = false
            })
          } else {
            addObj(this.tableOption).then(res => {
              if (res.data.code === 0) {
                this.$notify.success('添加成功')
                this.dialogLoading = false
                this.handleCancel()
              } else {
                this.$notify.error('添加失败')
                this.dialogLoading = false
                this.handleCancel()
              }
            }).catch(() => {
              this.dialogLoading = false
            })
          }
        }
      })
    },
    // 弹框取消
    handleCancel () {
      this.tableOption = {}
      this.dialogVisible = false
      this.isEdit = false
      this.getListData()
    },
    beforeClose (done) {
      this.handleCancel()
    },
    // 执行
    executionTask: function (row) {
      this.dialogLoading = true;
      executionObj(row.id)
        .then(data => {
          this.$notify.success("执行成功");
          this.getListData();
          this.dialogLoading = false;
        })
        .catch(() => {
          this.dialogLoading = false;
        });
    },
    //启用
    updateQStatus: function (row) {
      this.dialogLoading = true;
      getObj(row.id)
        .then(data => {
          this.$notify.success("修改状态成功");
          this.getListData();
          this.dialogLoading = false;
        })
        .catch(() => {
          this.dialogLoading = false;
        });
    },
    //暂停
    updateZStatus: function (row) {
      this.dialogLoading = true;
      getObj(row.id)
        .then(data => {
          this.$notify.success("修改状态成功");
          this.getListData();
          this.dialogLoading = false;
        })
        .catch(() => {
          this.dialogLoading = false;
        });
    },
    // 获取索引值
    getIndex (index) {
      const { current = 0, size = 0 } = this.pager
      return (current - 1) * size + (index + 1)
    }
  }
}
</script>
<style scoped lang="scss">
.task-dispatch {
  @include formWrap(2);
  /deep/ .dataList .cfilterRight {
    display: none;
  }
  .isPause {
    display: inline-block;
    text-align: center;
    width: 50px;
    height: 28px;
    line-height: 28px;
    border-radius: 5px;
    background-color: #ffeded;
    color: #ff4d4f;
    border-color: #ff4d4f;
  }
  .isPauseTrue {
    display: inline-block;
    text-align: center;
    width: 50px;
    height: 28px;
    line-height: 28px;
    border-radius: 5px;
    background-color: #eef9e8;
    color: #52c41a;
    border-color: #52c41a;
  }
}
</style>
